package com.zrrd.jt_admin.common.interceptor;

import com.alibaba.fastjson.JSON;
import com.zrrd.jt_admin.common.exception.TokenException;
import com.zrrd.jt_admin.common.response.ResponseResult;
import com.zrrd.jt_admin.common.utils.ContextHolder;
import com.zrrd.jt_admin.common.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author ZhangYK
 * @version 8.0
 * @title MyInttercetor
 * @description
 * @create 2024/6/28 23:09
 */
@Slf4j
public class MyInttercetor implements HandlerInterceptor {

    private final String TOKEN = "TOKEN_";


    @Resource
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.error("进入interceptor=========----------^&%%%%%%%$");
        String token = request.getHeader("token");
        Long id=-1l;
        try {
            if (StringUtils.isBlank(token)){
                log.debug("tokenIsNull");
                throw new TokenException("没有token，token为空");
            }
            //解析token
            Map<String, Object> map = JwtUtils.analysisToken(token);

            if (map==null){
                throw new TokenException("map为空");
            }
            //获取id
            id = Long.valueOf(map.get("id").toString());

            //去redis中验证
            String redisToken = redisTemplate.opsForValue().get(TOKEN + id);
            if (StringUtils.isBlank(redisToken)||!redisToken.equals(token)){
                log.error("token已失效");
                return false;
            }

            //在本地线程中添加id
            ContextHolder.setId(id);
            return true;
        }catch (TokenException e){
            log.info(e.getMessage());
            response.setContentType("application/json;charset=utf-8");
            ResponseResult responseResult = ResponseResult.defaultResponse(false, e.getMessage(), e.getMessage());
            String jsonString = JSON.toJSONString(responseResult);
            response.getWriter().print(jsonString);
            e.printStackTrace();
        }


        return false;
    }
}
